package server

import (
	"flag"
	"goland-study/go_code/raft_demo/pkg/raft"
	"log"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	id := flag.Int("id", 1, "Node ID")
	port := flag.Int("port", 50051, "Port number")
	config := flag.String("config", "cluster.json", "Cluster configuration file")
	flag.Parse()

	// 加载集群配置
	peers := loadClusterConfig(*config)

	// 创建持久化存储
	persister := raft.NewFilePersister(*id)

	// 创建状态机
	stateMachine := raft.NewKVStateMachine()

	// 创建应用通道
	applyCh := make(chan raft.ApplyMsg, 1024)

	// 创建Raft节点
	node := raft.MakeRaft(int32(*id), peers, *port, persister, applyCh)
	node.StateMachine = stateMachine

	// 启动Raft节点
	node.Start()

	// 处理应用消息
	go func() {
		for msg := range applyCh {
			if msg.CommandValid {
				// 应用命令到状态机
				_, _ = stateMachine.Apply(msg.Command)
			}
		}
	}()

	// 等待终止信号
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	<-sigCh

	// 停止节点
	node.Stop()
	log.Printf("Node %d stopped", *id)
}

func loadClusterConfig(file string) map[int32]string {
	// 实际实现中从文件加载
	return map[int32]string{
		1: "localhost:50051",
		2: "localhost:50052",
		3: "localhost:50053",
	}
}
